package com.kingschan.jeasytag.sql.query;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import com.kingschan.jeasytag.HttpQueryBean;
import com.kingschan.jeasytag.container.EasyTagContainer;
import com.kingschan.jeasytag.container.impl.EasyTagContainerImpl;
import com.kingschan.jeasytag.enums.DbType;
import com.kingschan.jeasytag.sql.connection.ConnectionFactory;
import com.kingschan.jeasytag.sql.parse.FieldTypeAnalysis;
import com.kingschan.jeasytag.sql.parse.QueryArgsAnalysisFactory;
import com.kingschan.jeasytag.tag.power.SQLTag;
import com.kingschan.util.bean.BeanUtil;
import com.kingschan.util.lang.StringUtil;
/**
 * 
 * @author kingschan
 *date:2013-7-11
 */
public class BuilderSqlQueryBean {

	private HttpQueryBean hqb ;
	private SqlQueryBean sqb;
	private EasyTagContainer container=EasyTagContainerImpl.getInstance();
	private static Logger log = Logger.getLogger(BuilderSqlQueryBean.class);
	private SQLTag sqltag;
	public BuilderSqlQueryBean(HttpQueryBean p_hqb){
		this.hqb=p_hqb;
		sqb = new SqlQueryBean();
	}
	
	public SqlQueryBean buliderSqlQueryBean() throws Exception{
		init();
		return this.sqb;
	}
	
	void init() throws Exception{
		log.debug("Serialization sqltag ");
		String path=container.getSerializationPath().concat(hqb.getSerialization()).concat(".data");
		sqltag = (SQLTag) BeanUtil.DesSerializationObject(path);
		log.debug(" get connection");
		Connection conn =ConnectionFactory.getConn(sqltag.getJdbcConnection(), container.getDefaultConnection());
		
		log.debug(" init order by...");
		String sort=hqb.getHttpargs().containsKey("sort")?
				hqb.getHttpargs().get("sort")+" "+hqb.getHttpargs().get("order")
				:null;
		List<String> order_lis =new ArrayList<String>();
		if (!"".equals(StringUtil.ConvertNullStr(sort))) {
			order_lis.add(sort);
		}
				
				
				
		sqb.setDbtype(DbType.valueOf(sqltag.getDBtype()));		
		sqb.setConnection(conn);
		sqb.setOrder_by(order_lis);
		sqb.setPage_index(hqb.getPageindex());
		sqb.setPage_size(hqb.getPagesize());
		sqb.setSql_command(sqltag.getSql());
		sqb.setWhere_str(getFilter());
		
	}
	
	/**
	 * bulider where str
	 * @return
	 * @throws Exception
	 */
	String getFilter() throws Exception{	
		log.debug("init where str");
		if (null==hqb.getCondition()) {
			return "";
		}
			JSONArray jsons = hqb.getCondition();		
			Map<String, String> map =this.builderMetaData();
			StringBuffer and_str= new StringBuffer();
			StringBuffer or_str= new StringBuffer();
			String current_field=null;
			String analysis_str="";
			for (int i = 0; i < jsons.length(); i++) {
				 current_field =jsons.getJSONObject(i).getString("filterfield");				 
				FieldTypeAnalysis fta =QueryArgsAnalysisFactory.getAnalysis(map.get(current_field));				
				if (jsons.getJSONObject(i).getString("relationship").equals("or")) {
					analysis_str=fta.Analysis(jsons.getJSONObject(i), sqb.getDbtype());
					if(!"".equals(StringUtil.ConvertNullStr(analysis_str))){
						or_str.append(" or ("). append(analysis_str).append(") ");
					}					
				}else{
					analysis_str=fta.Analysis(jsons.getJSONObject(i), sqb.getDbtype());
					if(!"".equals(StringUtil.ConvertNullStr(analysis_str))){
						and_str.append(" and (").append(analysis_str).append(") ");
					}
				}
			}
		
			return and_str.toString().concat(or_str.toString());
		
	}
	
	
	public Map<String, String> builderMetaData() throws Exception{		
		log.debug("init query field info");
		Map<String, String> map = new HashMap<String, String>();
		if (null!=hqb.getMetadate()) {
			JSONArray jsons = hqb.getMetadate()	;
			for (int i = 0; i < jsons.length(); i++) {			
				map.put(jsons.getJSONObject(i).getString("filed"), jsons.getJSONObject(i).getString("editor"));
			}
		}
		return map;
		
	}
}
